package top.hzy520.payment.alipay.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.hzy520.payment.alipay.dao.PayInfoMapper;
import top.hzy520.payment.alipay.dto.Order;
import top.hzy520.payment.alipay.dto.RefundInputDto;
import top.hzy520.payment.alipay.entity.PayInfo;
import top.hzy520.payment.alipay.feign.OrderService;
import top.hzy520.payment.config.AlipayConfig;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 21:49 2018/9/15
 */
@Slf4j
@Service
public class AliPayServiceImpl implements AliPayService {
    private static final String TRADE_FINISHED = "TRADE_FINISHED";
    private static final String TRADE_SUCCESS = "TRADE_SUCCESS";
    private static final String NOTIFY_SUCCESS ="success" ;
    private static final String NOTIFY_FAIL = "fail";
    private static final String REFUND_RESPONSE = "alipay_trade_refund_response";
    private static final String REFUND_CODE = "code";
    @Autowired
    private PayInfoMapper payInfoMapper;

    @Autowired
    private OrderService orderService;


    /***
     *
     * @param order 订单信息
     * @param response
     * @return 支付页面结果
     */
    @Override
    public void alipayPcPay(Order order, HttpServletResponse response) {
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no =order.getOrderNo().toString();
        //付款金额，必填
        String total_amount = order.getPayment().toString();
        //订单名称，必填
        String subject =  order.getOrderSubject() ;
        //商品描述，可空
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        try {
            //请求支付页面
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            //输出
            response.setContentType("text/html;charset=" + AlipayConfig.charset);
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(result);
            response.getWriter().flush();
        } catch (Exception e) {
             log.error("订单编号:"+out_trade_no+"请求支付异常",e);
        }
    }

    /**
     * 异步处理支付结果
     * @param request
     * @param response
     */
    @Override
    @Transactional
    public void notifyUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]: valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes(Charset.defaultCharset()), "utf-8");
            params.put(name, valueStr);
        }
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        Order order=new Order();
        order.setOrderNo(Long.valueOf(out_trade_no));
        String subject=orderService.queryOrderSubject(order);
        params.put("subject",subject);
        boolean signVerified = false;
        try {
            //调用SDK验证签名
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            log.error("订单编号:"+out_trade_no+"验签出现异常",e);
        }
        if(signVerified){
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

            log.info("订单号："+out_trade_no+"--支付宝交易号码："+trade_no+"--交易状态："+trade_status);

            if(trade_status.equals(TRADE_FINISHED)){
                //支付失败业务

            }else if (trade_status.equals(TRADE_SUCCESS)){
                //支付成功则关闭订单 并 修改订单状态
                orderService.verifyOrderStatus(order);
                //插入订单支付表
                PayInfo payInfo=new PayInfo();
                payInfo.setOrderNo(Long.valueOf(out_trade_no));
                payInfo.setTradeNo(Long.valueOf(trade_no));
                payInfoMapper.insertSelective(payInfo);
            }
            response.getOutputStream().println(NOTIFY_SUCCESS);
        }else {
            log.info("订单编号:"+out_trade_no+"验签失败");
            //验证失败
            response.getOutputStream().println(NOTIFY_FAIL);
        }
    }

    /**
     *
     * @param refundInputDto 退款信息
     * @return 退款返回码
     * @throws AlipayApiException
     */
    @Override
    public String reFund(RefundInputDto refundInputDto) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

        //商户订单号，商户网站订单系统中唯一订单号
        String out_trade_no = String.valueOf(refundInputDto.getOutTradeNo());
        //支付宝交易号
        String trade_no = String.valueOf(refundInputDto.getTradeNo());
        //请二选一设置
        //需要退款的金额，该金额不能大于订单金额，必填
        String refund_amount = String.valueOf(refundInputDto.getRefundAmount());
        //退款的原因说明
        String refund_reason =refundInputDto.getRefundReason();
        //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
        String out_request_no = String.valueOf(refundInputDto.getOutRequestNo());

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"trade_no\":\""+ trade_no +"\","
                + "\"refund_amount\":\""+ refund_amount +"\","
                + "\"refund_reason\":\""+ refund_reason +"\","
                + "\"out_request_no\":\""+ out_request_no +"\"}");

        //请求
        String result = alipayClient.execute(alipayRequest).getBody();
        JSONObject jsonObject=JSONObject.parseObject(result);
        JSONObject jsonObject1= (JSONObject) jsonObject.get(REFUND_RESPONSE);
        String code= (String) jsonObject1.get(REFUND_CODE);
        if ("10000".equals(code)){
           log.info("订单编号:"+out_trade_no+"----"+"支付宝编号:"+trade_no+"退款成功");
        }else {
            log.info("订单编号:"+out_trade_no+"----"+"支付宝编号:"+trade_no+"退款失败");
        }
        return code;
    }
}
